package image.review.handlers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Mads
 */
public class IOHandler {
    
    public static File[] getFilesInDirectory(File path) throws NullPointerException {
        
        if (path == null || !path.exists()) {
            throw new NullPointerException("Path defined is invalid\nPath: " + path.getAbsolutePath());
        }
        
        List<File> list = new ArrayList<File>();   
        
        searchDirectory(list, path);
        
        File[] returnFiles = new File[list.size()];
        
        for (int i = 0; i < list.size(); i++) {
            returnFiles[i] = list.get(i);
        }
        
        return returnFiles;
    }
    
    public static File[] returnExtensionsOnly(File[] files, String[] extensions) {

        List<File> list = new ArrayList<>();
        String ext;

        for (int i = 0; i < files.length; i++) {

            ext = files[i].getPath().substring(files[i].getPath().lastIndexOf('.') + 1);

            for (int j = 0; j < extensions.length; j++) {

                if (ext.equalsIgnoreCase(extensions[j])) {
                    
                    list.add(files[i]);
                }
            }
        }

        files = new File[list.size()];

        for (int i = 0; i < list.size(); i++) {
            files[i] = list.get(i);
        }

        return files;
    }
    
    private static void searchDirectory(List<File> list, File file) {
        
        if(file.isFile()) {
            list.add(file);
        }
        else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                searchDirectory(list, files[i]);
            }            
        }
    }
    
    public static boolean deleteFile(File file) {
        try {
            file.delete();
        }
        catch (Exception e) {
            return false;
        }
        return true;
    }
}
